<%@ page import="com.cgah.Listing" %>
<%@ page import="com.cgah.Constants" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="layout" content="main"/>
    <g:set var="entityName" value="${message(code: 'listing.label', default: 'Listing')}"/>
    <title><g:message code="default.show.label" args="[entityName]"/></title>
</head>
<body>
<div class="nav"><span class="spacer"></span>
    %{--<span class="menuButton"><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></span>--}%
    <span class="menuButton"><g:link class="list" action="list"><g:message code="default.list.label" args="[entityName]"/></g:link></span>
    <span class="menuButton"><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]"/></g:link></span>
</div>
<div class="body">
    <h1><g:message code="default.show.label" args="[entityName]"/></h1>
    %{--<g:if test="${flash.message}">--}%
        <div name="statusMessage" style="visibility:hidden;display:block;" id="statusMessage" class="message">${flash.message}</div>
    %{--</g:if>--}%

    <div class="dialog" style="width:100%;">
        <table>
            <tr>
            <td>
                <span>Listing Details</span>
                <table>
                    <tbody>

                    <tr class="prop">
                        <td valign="top" class="name"><g:message code="listing.id.label" default="Id"/></td>
                        <td valign="top" class="value">${fieldValue(bean: listingInstance, field: "id")}</td>
                    </tr>
                    <tr class="prop">
                        <td valign="top" class="name"><g:message code="listing.name.label" default="Name"/></td>
                        <td valign="top" class="value">${fieldValue(bean: listingInstance, field: "name")}</td>
                    </tr>
                    <tr class="prop">
                        <td valign="top" class="name"><g:message code="listing.endDateTime.label" default="End Date Time"/></td>
                        <td valign="top" class="value" style="white-space:nowrap;"><g:formatDate format="${Constants.DATE_TIME_FORMAT}" date="${listingInstance?.endDateTime}"/></td>
                    </tr>
                    <tr class="prop">
                        <td valign="top" class="name"><g:message code="listing.startingBidPrice.label" default="Starting Bid Price"/></td>
                        <td valign="top" class="value">${fieldValue(bean: listingInstance, field: "startingBidPrice")}</td>
                    </tr>

                    <tr class="prop">
                        <td valign="top" class="name"><g:message code="listing.seller.label" default="Seller"/></td>
                        <td valign="top" class="value">
                            <g:link controller="customer" action="show" id="${listingInstance?.seller?.id}">
                            %{--no need to check existance of @ because it's required on data entry--}%
                                ${listingInstance?.seller?.shortName}
                            %{--${listingInstance?.seller?.encodeAsHTML()}--}%
                            </g:link>
                        </td>
                    </tr>

                    <tr class="prop">
                        <td valign="top" class="name"><g:message code="listing.description.label" default="Description"/></td>
                        <td valign="top" class="value">${fieldValue(bean: listingInstance, field: "description")}</td>
                    </tr>

                    <tr class="prop">
                        <td valign="top" class="name"><g:message code="listing.winner.label" default="Winner"/></td>
                        <td valign="top" class="value"><g:link controller="customer" action="show" id="${listingInstance?.winner?.id}">${listingInstance?.winner?.encodeAsHTML()}</g:link></td>
                    </tr>

                    <tr class="prop">
                        <td valign="top" class="latestBid"><g:message code="listing.latestBid" default="Latest Bid"/></td>
                        <td valign="top" class="value">
                            <g:if test="${!listingInstance.bids?.empty}">
                                <label id="latestBid">
                                    ${listingInstance.latestBid?.encodeAsHTML()}
                                </label>
                            </g:if>
                            <g:else>
                                <label id="latestBid">
                                    No bids yet
                                </label>
                            </g:else>
                        </td>
                    </tr>
                   </tbody>
                </table>
            </td>
            <td>
                <span>Last 10 bids</span>
                <div>
                    <!-- don't mess with this! I don't want to write a complicated JS dammit -->
                    <table id="bidHistory" style="white-space:nowrap;">
                        <tr></tr><th>User</th><th>Date/Time</th><th>Amount</th></tr>
                        <g:each in="${listingInstance.lastTenBids}" var="b">
                            <tr>
                                <td>
                                    ${b.customer.username}
                                </td>
                                <td>
                                    ${com.cgah.DateNumberFormatter.formatDate(b.dateTime)}
                                </td>
                                <td>
                                    $${com.cgah.DateNumberFormatter.formatNumber(b.amount)}
                                </td>
                            </tr>
                        </g:each>
                    </table>
                </div>
            </td>
            </td>
                <sec:ifAllGranted roles="${Constants.ROLE_USER}">
                <td>
                    <span>Place new bid</span>
                    %{--<g:form action="addBid" controller="bid"  >--}%
                    <div>
                        %{--<g:hiddenField name="listing.id" value="${listingInstance?.id}"/>--}%

                        <table>
                            <tbody>
                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="minbid"><g:message code="bid.minbid.label" default="Minimum Bid"/></label>
                                </td>
                                <td valign="top" class="value">
                                    <g:textField name="minbid" id="minbid" value="${listingInstance.latestBid?.nextMinBid}"/>
                                </td>
                            </tr>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="amount"><g:message code="bid.amount.label" default="Amount"/></label>
                                </td>
                                <td valign="top" class="value">
                                    <g:textField name="amount" id="amount" value="${listingInstance.latestBid?.nextMinBid}"/>
                                </td>
                            </tr>

%{--
                            // no need any longer, bids always go against the logged in person
                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label><g:message code="bid.customer.label" default="Customer"/></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: bidInstance, field: 'customer', 'errors')}">
                                    <g:select name="customer.id"
                                            from="${com.cgah.Customer.list()}"
                                            optionKey="id"
                                        optionValue="shortName"
                                            value="${bidInstance?.customer?.id}"/>
                                </td>
                            </tr>
--}%

                            </tbody>
                        </table>
                        <div class="buttons">
                            <span class="button">
                                <input type="button" onclick="asyncSubmitBid();" name="create"
                                        class="create"
                                        value="${message(code: 'default.button.newBid.label', default: 'New Bid')}"/>
                                %{--<g:submitButton onclick="asyncSubmitBid();" name="create" class="create" value="${message(code: 'default.button.newBid.label', default: 'New Bid')}"/>--}%

                            </span>
                        </div>
                    %{--</g:form>--}%
                    </div>
                </td>
                </sec:ifAllGranted>
        </tr>
        </table>
        <g:render template="/templates/editDelete" model="['customerId':listingInstance.seller?.id,'targetId':listingInstance?.id, 'showAdmin':0]"/>
    </div>
</div>
<script type="text/javascript">
<!--
var hidesuccesstimer = null;

function updateBidFields(bid) {
    // in the case where there is no bids on the listing we don't blow up
    if (bid) {
    //alert('asdf ' + bid.nextMinBid.toFixed(2))
    $("#amount").val(bid.nextMinBid.toFixed(2));
    $("#minbid").val(bid.nextMinBid.toFixed(2));
    // whatever, formatting this sux! with JS sooooo
    $("#latestBid").html(bid.dateTimeString + ' ' + bid.amount.toFixed(2));
    }
}

function hideSuccessMessage() {
    $("#statusMessage").hide(5);
}

function updateStatusMessage(message) {
    $("#statusMessage").css('visibility','visible');
    $("#statusMessage").css('display', 'block');
    $("#statusMessage").html(message);
}


////////////////// all functions related to making an async bid ///////////////////////////////////////////////////////
function successBid(data) {
    updateStatusMessage(data.message);
    updateBidFields(data.bid);
    if (hidesuccesstimer) {
        clearTimeout(hidesuccesstimer);
    }
    setTimeout(hideSuccessMessage, 60000); // in 1 min hide the message
}

function asyncSubmitBid() {
    var amount = jQuery("#amount").val();
     $.ajax({
        url:"${request.contextPath}/bid/asyncAddBid",
        dataType: 'json',
        data: {
            'listing.id': ${listingInstance.id},
            amount: jQuery("#amount").val(),
        },
        success: successBid,
        error: function(request, status, error) {
            //alert('request: ' + request + '\r\nstatus:' + status + '\r\nerror : ' + error + '\r\nresponse: ' + request.responseText)
            // just show the custom error for now
            updateStatusMessage(request.responseText);
        },
        complete: function() {
            // what to do what to do?
        }
    });



}


//////////////////////////////// all functions related to auto refreshing the bid list ////////////////////////////////
var bidHistoryTable = null;
var bidHistoryTableTimer = null;

function redrawBidHistoryTable(data) {
    if (!bidHistoryTable) {
        bidHistoryTable = $("#bidHistory");
    }
    // make sure we actually got a handle to the table.
    if (bidHistoryTable) {
        // TODO loop through jsonData and redraw the table.
        var tableRowStr = '';
        var result = new Array();

        // there was only 1 object returned, not a list
        if (data.id) {
            result[0] = data;
        } else {
            // an array was returned.
            result = data;
        }
        updateBidFields(result[0]);
        for (var i = 0; i < result.length; i++) {  // now.format("longTime", true);  .format("longTime");
            //Date d = new Date()
            tableRowStr +=
                    '<tr><td>' + result[i].username + ' </td><td>  '
                    + result[i].dateTimeString + ' </td><td> $'
                    + result[i].amount.toFixed(2)  + '</td></tr>';
        }
        bidHistoryTable.find("tr:gt(1)").remove();
        bidHistoryTable.append($(tableRowStr));
    }
}


function successBidHistoryTable(data) {
    redrawBidHistoryTable(data);

    if (bidHistoryTableTimer) {
        clearTimeout(bidHistoryTableTimer);
    }
    bidHistoryTableTimer = setTimeout (asyncUpdateBidHistoryTable, 2500);
}


function asyncUpdateBidHistoryTable() {
    //alert('calling ' + asyncUpdateBidHistoryTable);
    $.ajax({
        url:"${request.contextPath}/listing/lastTenBids",
        dataType: 'json',
        data: {
            id: ${listingInstance.id},
        },
        success: successBidHistoryTable,
        error: function(request, status, error) {
            //alert('request: ' + request + '\r\nstatus:' + status + '\r\nerror : ' + error)
            updateStatusMessage('Error updating bids.  Status:' + status + ' Error : ' + error);
        },
        complete: function() {
            // what to do what to do?
        }
    });
}

    $(document).ready(function () {
        $("#username").focus();
        setTimeout (asyncUpdateBidHistoryTable, 2500);
        if ('${flash.message}' != '') {
            updateStatusMessage('${flash.message}');
        }
    });

    $(document).unload(function () {
        // make sure this damm thing stops, i know it's suppose to.
        clearTimeout(bidHistoryTableTimer);
    })

//-->
</script>


</body>
</html>
